<template>
  <div
    class="w-echarts"
    style="display:flex;flex-direction:column;justify-content:center;width:100%;margin-bottom:20px;"
    :style="{ height: height + 34 + 'px' }"
  >
    <div
      class="w-echarts-box"
      style="display:flex;justify-content:center;width:100%;border: 1px solid #ccc;"
      :style="{ height: height + 'px' }"
    >
      <!-- 图表 -->
      <div
        :id="id"
        :style="{ width: width + 'px', height: height + 'px' }"
        class="charts"
      ></div>
    </div>
    <div style="margin-top:10px;font-size:12px;text-align:center">
      图：{{ titleName }}
    </div>
  </div>
</template>
<script>
import chartMixins from '../components/mixins/chartMixins'
export default {
  props: {
    id: {
      type: String
    },
    width: {
      type: Number
    },
    height: {
      type: Number
    },
    itemData: {}
  },
  mixins: [chartMixins],
  data() {
    return {
      myEcharts: null,
      chartData: {},
      titleName: ''
    }
  },
  watch: {
    itemData: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        if (newVal != {}) {
          this.chartData = this.initChart(newVal)
          this.titleName = newVal.name
        } else if (oldVal) {
          this.chartData = this.initChart(oldVal)
          this.titleName = oldVal.name
        }
        this.setOption(this.chartData)
      }
    }
  },
  mounted() {
    if (this.id != '') {
      this.initCharts()
      window.addEventListener('resize', () => {
        this.setThrottling()
      })
    }
  },
  methods: {
    chartresize() {
      if (this.myEcharts !== null) {
        this.myEcharts.resize()
      }
    },
    // 防抖
    setThrottling() {
      clearTimeout(this.throttleTimer)
      this.throttleTimer = setTimeout(() => {
        this.chartresize()
      }, 200)
    },
    initCharts() {
      // 初始化echarts
      this.myEcharts = this.echarts.init(document.getElementById(this.id))
      if (this.chartData) {
        this.setOption(this.chartData)
      }
      this.myEcharts.on('click', params => {
        this.$emit('echartsClick', params)
      })
    },
    setOption(option) {
      this.$nextTick(() => {
        this.myEcharts.setOption(this.chartData, true)
      })
    }
  }
}
</script>
<style scoped></style>
